package com.yun.zf.admin.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicParameters;
import com.yun.zf.admin.excelListener.UploadAgentListener;
import com.yun.zf.common.admin.domain.SysAgent;
import com.yun.zf.common.admin.domain.SysUser;
import com.yun.zf.common.admin.model.SysAgentEditMo;
import com.yun.zf.common.admin.model.sys.AgentAddMo;
import com.yun.zf.common.admin.model.sys.AgentBasicMo;
import com.yun.zf.common.admin.model.sys.AgentEditMo;
import com.yun.zf.common.admin.model.sys.AgentSearchMo;
import com.yun.zf.common.annotation.LogPrint;
import com.yun.zf.common.app.domain.SysUserAuth;
import com.yun.zf.common.vo.Response;
import com.yun.zf.system.security.utils.SecurityUtils;
import com.yun.zf.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/system/agent")
@Api(value = "", tags = "经纪人管理")
@Log
public class SysAgentController {
    @Autowired
    private SysAgentService agentService;
    @Autowired
    private SysUserAuthService userAuthService;
    @Autowired
    private SysUserRoleService userRoleService;
    @Autowired
    private SysPostService postService;
    @Autowired
    private UploadAgentListener agentListener;
    @Autowired
    private ISysUserService userService;


    /**
     * 业务员信息管理，只有admin 角色和 manager 角色才能查看管理
     *
     * @return
     */
    @PostMapping("/agentList")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @ApiOperation(value = "经纪人列表")
    @LogPrint(description = "经纪人列表")
    public Response getAgentList(@RequestBody AgentSearchMo searchMo) {
        return Response.success(agentService.getAgentList(searchMo));
    }

    @GetMapping("/getAgentInfo")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @ApiOperation(value = "经纪人详细信息")
    @LogPrint(description = "经纪人详细信息")
    public Response getAgentInfo(int id, Long userId) {

        // 获取经纪人信息
        SysAgent agent = agentService.getAgent(userId, id);
        if (agent == null) {
            return Response.error("未查询到经纪人信息");
        }
        // 拼接城市
        String[] city = {String.valueOf(agent.getProvinceCode()) ,String.valueOf(agent.getCityCode())};
        agent.setCity(city);
        //拼接部门
        // 获取角色，岗位信息
        List<Long> roleIds = userRoleService.getRoleId(userId);
        // 获取岗位信息
        Long postId = postService.getUserPost(userId);
        Map<String, Object> map = new HashMap();
        map.put("agent", agent);
        map.put("roleIds", roleIds);
        map.put("postId", postId);
        return Response.success(map);
    }

    @PostMapping("/getDeptAndRole")
    @ApiOperation(value = "角色，岗位信息")
    @LogPrint(description = "角色，岗位信息")
    public Response getDeptAndRole() {
        //todo ,待修改
        SysAgentEditMo editMo = agentService.getEditInfo();
        return Response.success(editMo);
    }

    /**
     * 修改经纪人信息
     *
     * @param
     * @return
     */
    @PostMapping("/upAgentInfo")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @LogPrint(description = "修改经纪人信息")
    @ApiOperation(value = "修改经纪人信息")
    public Response upAgentInfo(@Validated @RequestBody AgentEditMo editMo) {

        SysAgent agent = agentService.getAgent(editMo.getUserId(), editMo.getId());
        if (agent == null) {
            return Response.error("经纪人不存在");
        }
        //1 验证是否已经离职，如果离职则不允许切换
        int count = agentService.checkIsDelFlag(agent.getId());
        if (count == 0) {
            return Response.error("经纪人已经离职，不允许在进行状态修改");
        }

        // 城市不能修改
        if (!String.valueOf(agent.getCityCode()).equals(editMo.getCity()[1]) || !String.valueOf(agent.getProvinceCode()).equals(editMo.getCity()[0])) {
            return Response.error("不允许切换城市");
        }
        // 部门不能修改
        //获取部门级联
       /* JSONArray deptIds = JSONObject.parseArray(editMo.getDeptIds());
        String deptId="";
        if (deptIds.size() == 1) {
            deptId =deptIds.get(0).toString();
        } else if (deptIds.size()  == 2) {
            deptId =deptIds.get(1).toString();
        }
        if (!agent.getDeptId().equals(deptId)){
            return Response.error("不允许更换部门");
        }*/
        Boolean flage = agentService.motifyAgent(editMo, agent);
        if (flage) {
            return Response.success(flage);
        }
        return Response.error("更新失败");
    }

    /**
     * 新增经纪人信息, 经纪人只能根据模板导入，必须携带城市区划代码和工号
     *
     * @param agentMo
     * @return
     */
    @PostMapping("/addAgentInfo")
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @ApiOperation(value = "新增经纪人")
    @LogPrint(description = "新增经纪人")
    public Response addAgentInfo(@Validated @RequestBody AgentAddMo agentMo) {
        // 验证经纪人是否存在
        SysAgent agent = agentService.checkUniAgent(agentMo.getCardNo(), agentMo.getIphone());
        if (agent != null) {
            return Response.error("当前人员信息已存在，请勿重复添加");
        }
        //2、 根据手机号码获取用户id
        SysUserAuth userPhone = userAuthService.getUserByIphone(Long.parseLong(agentMo.getIphone()));
        if (userPhone == null) {
            return Response.error("还未注册，请先注册为平台用户");
        }
        int count = agentService.addAgentAny(agentMo, userPhone.getUserId());
        if (count > 0)
            return Response.success();
        else
            return Response.error("添加失败");
    }


    @GetMapping("/changeSatus")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @ApiOperation(value = "切换经纪人状态")
    @LogPrint(description = "切换经纪人状态")
    public Response changeSatus(int id, int status) {
        try {
            //1 验证是否已经离职，如果离职则不允许切换
            int count = agentService.checkIsDelFlag(id);
            if (count == 0) {
                return Response.error("经纪人已经离职，不允许在进行状态修改");
            }
            agentService.changeStatus(id, status);
            return Response.error("状态修改成功");
        } catch (Exception e) {
            return Response.error("状态修改失败");
        }
    }


    @GetMapping("/delAgentInfo")
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @ApiOperation(value = "删除经纪人信息")
    @LogPrint(description = "删除经纪人信息")
    public Response delAgentInfo(long id) {
        log.info("删除的经纪人Id--------" + id);
        try {
            agentService.motifyAgentById(id);
            return Response.success("删除成功");
        } catch (Exception e) {
            return Response.error("删除失败");
        }
    }

    @PostMapping(value = "/excelAgent")
    @ApiOperation(value = "经纪人导入")
    @LogPrint(description = "经纪人导入")
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    public Response excelAgent(@RequestParam(value = "agentFile", required = false) MultipartFile file) {
        try {
            //获得工作簿
            ExcelReaderBuilder read = EasyExcel.read(file.getInputStream(), AgentAddMo.class, agentListener);
            //获得工作表  又两种形形式可以通过下标也可以通过名字2003Excel不支持名字
            ExcelReaderSheetBuilder sheet = read.sheet();
            //进行读操作
            sheet.doRead();
            return Response.success();
        } catch (Exception e) {
            return Response.error(e.getMessage());
        }
    }


    @PostMapping("/getUser")
    @ApiOperation(value = "用户信息查询")
    @LogPrint(description = "用户信息查询")
    public Response getUser() {
      return  Response.success(agentService.getUserBasic());
    }

    @PostMapping("/editUser")
    @ApiOperation(value = "用户信息修改")
    @LogPrint(description = "用户信息修改")
    public Response editUser(@Validated @RequestBody AgentBasicMo agentMo) {
        // 根据userId 查找当前用户
      int c =  agentService.editUser(agentMo);
      if (c>0)
          return  Response.success();
      else
          return Response.error("修改失败");
    }

    @PostMapping("/editPassword")
    @ApiOperation(value = "用户密码修改")
    @LogPrint(description = "用户密码修改")
    @DynamicParameters(properties = {
            @DynamicParameter(name = "oldPass",value = "原密码",example = "111",required = true),
            @DynamicParameter(name = "newPass",value = "新密码",example = "111",required = true)
    })
    public Response editPassword(@RequestBody Map<String,String> map) {
        // 验证原密码是否正确
     SysUser user = userService.getUserById(SecurityUtils.getLoginUser().getUserId());
     String old = map.get("oldPass");
     String newPass = map.get("newPass");
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
       if (!encoder.encode(old).equals(user.getPassword())){
           return  Response.error("密码不正确");
       }
       userService.editPassword(old,newPass);
        return  Response.success();
    }

}
